package SinglyLinkedList.SentinelLinkedList;

import java.util.function.Consumer;

public class SentinelLinkedList {
  Node head = new Node(666, null); // 哨兵

  private static class Node {
    int value;
    Node next;

    public Node(int value, Node next) {
      this.value = value;
      this.next = next;
    }
  }

  public void addFirst(int value) {
    head.next = new Node(value, head.next); // 改动, 要保证哨兵始终在头部
  }

  public void addLast(int value) {
    Node last = findLast();
    last.next = new Node(value, null);
  }

  public int remove(int index) {
    Node pervious = findNode(index - 1);
    Node current = pervious.next;
    if (current == null) {
      return -1;
    }
    int value = current.value;
    pervious.next = current.next;
    return value;
  }

  public int getValue(int index) {
    Node p = findNode(index);
    if (p == null) {
      return -1;
    }
    return p.value;
  }

  public void insert(int value, int index) {
    Node pervious = findNode(index - 1);
    pervious.next = new Node(value, pervious.next);
  }

  private Node findNode(int index) {
    Node p = head; // 改动, 哨兵(index = -1)开始找
    int i = -1;
    while (p != null) {
      if (i == index) {
        return p;
      }
      p = p.next;
      i++;
    }
    return null;
  }

  public void loop(Consumer <Integer> consumer) {
    for (Node node = head.next; node != null; node = node.next) { // 改动, 要跳过head, 也就是哨兵
      consumer.accept(node.value);
    }
  }

  private Node findLast() {
    Node p = head;
    while (p.next != null) {
      p = p.next;
    }
    return p;
  }
}
